var controller;
var landingDisenyo = function() {
  if ($(window).width() >= 768) {
    controller = new ScrollMagic.Controller();

    // Add class design-comparte__left
    new ScrollMagic.Scene({
      triggerElement: ".js-design-comparte-left",
      triggerHook: 0.6
    })
      .setClassToggle(".js-design-comparte__title", "is-active")
      // .addIndicators()
      .addTo(controller);

    // Add class design-comparte__left
    new ScrollMagic.Scene({
      triggerElement: ".js-design-panels-right",
      triggerHook: 0.6
    })
      .setClassToggle(".js-design-panels__title", "is-active")
      // .addIndicators()
      .addTo(controller);

    // Add class design-comparte__left
    new ScrollMagic.Scene({
      triggerElement: ".js-design-gracias",
      triggerHook: 0.6
    })
      .setClassToggle(".js-design-gracias-line", "is-active")
      // .addIndicators()
      .addTo(controller);

    function fadeAnimation(id) {
      return new TimelineMax().fromTo(
        id + " .design-panels__content",
        1,
        { x: "100%" },
        { x: "0%", ease: Linear.easeNone }
      );
    }

    // Affix design panels
    new ScrollMagic.Scene({
      triggerElement: ".js-panel-wrap",
      triggerHook: 0
    })
      .setClassToggle(".js-design-panels-right", "affix")
      // .addIndicators({name: 'affix'})
      .addTo(controller);

    // Affix design panels
    $(".js-panel").each(function() {
      var name = $(this).attr("id");

      new ScrollMagic.Scene({
        triggerElement: this,
        duration: $(this).outerHeight(true) / 3,
        offset: -60,
        triggerHook: 0,
        tweenChanges: false
      })
        .setPin(this)
        .setTween(fadeAnimation("#" + name))
        // .addIndicators({ name:name })
        .addTo(controller);
    });

    // Affix design panels
    new ScrollMagic.Scene({
      triggerElement: ".js-design-gracias",
      triggerHook: "onEnter"
    })
      .setClassToggle(".js-design-panels-right", "affix-bottom")
      // .addIndicators({name: 'affix-bottom'})
      .addTo(controller);

    $(".js-design-comparte-item").each(function() {
      var name = $(this).attr("id");
      new ScrollMagic.Scene({ triggerElement: this })
        .setClassToggle(this, "is-active")
        .loglevel(3)
        .addTo(controller);
    });

    $("body").scrollspy({
      target: "#navbar",
      offset: 60
    });

    $("#navbar ul li a[href^='#']").on("click", function(e) {
      e.preventDefault();
      var hash = this.hash;
      $("html, body").animate(
        {
          scrollTop: $(this.hash).offset().top
        },
        1000,
        function() {
          //window.location.hash = hash
        }
      );
    });
  }
};

var destroyLandingDisenyo = function() {
    controller.destroy(true);
    controller = null;
    scene = null;
    tween = null;
};


$(document).ready(function()
{
    $('.btn_product_category').on('click', function()
    {
        _btn = $(this).data('btn');

        if( _btn == 'todos' )
        {
            // product
            $('.product').show();
        }

        if( _btn == 'destacados' )
        {
            // product_destacados_actiu
            $('.product').hide();
            $('.product_destacados_actiu').show();
        }

        if( _btn == 'novedades' )
        {
            // product_novedades
            $('.product').hide();
            $('.product_novedades').show();
        }
    });

    $('.btn_product_home').on('click', function()
    {
        _btn = $(this).data('btn');

        if( _btn == 'destacados' )
        {
            // product_destacados_actiu
            $('.home_product_novedades').hide();
            $('.home_product_destacados_actiu').show();
        }

        if( _btn == 'novedades' )
        {
            // product_novedades
            $('.home_product_destacados_actiu').hide();
            $('.home_product_novedades').show();
        }
    });

    // ocultamos las novedades por js
    $('.home_product_novedades').hide();


    $('.js-gallery-bt-more-custom').on('click', function(ev){
        ev.preventDefault();
        var num = $(this).data('nmore');

        var t=$(this).closest(".js-gallery-wrap").find(".js-gallery-item.hidden").first();
        $(this).closest(".js-gallery-wrap").find(".js-gallery-item.hidden:lt("+num+")").removeClass("hidden");
        $("html, body").animate({scrollTop:t.offset().top-$(".js-main-header").outerHeight()},300);
        if($(this).closest(".js-gallery-wrap").find(".js-gallery-item.hidden").length === 0)
            $(".js-gallery-buttons").hide();
    });


    $('.js-btn-more-news').on('click', function(ev){
        ev.preventDefault();
        var num = $(this).data('nmore');

        var t=$(".news.hidden").first();
        $(".news.hidden:lt("+num+")").removeClass("hidden");
        $("html, body").animate({scrollTop:t.offset().top-$(".js-main-header").outerHeight()},300);
        if($(".news.hidden").length === 0)
            $(".news__buttons").hide();
    });


    $('.js-bt-more-products-designer').on('click', function(ev)
    {
        ev.preventDefault();
        var num = $(this).data('nmore');

        var t=$(this).closest(".js-bt-more-products-section").find(".product.hidden").first();
        $(this).closest(".js-bt-more-products-section").find(".product.hidden:lt("+num+")").removeClass("hidden");
        // $("html, body").animate({scrollTop:t.offset().top-$(".js-main-header").outerHeight()},300);
        if($(this).closest(".js-bt-more-products-section").find(".product.hidden").length === 0)
            $(".buttons-more-bottom").hide();
    });



    // Abrir elementos inline
    $('.js-show-hide-inline').on('click', function(ev) {
        ev.preventDefault();
        var item_show  = $(this).attr('href');
        var item_hide  = $(this).attr('rel');
        $(this).toggleClass('is-active');

        $(item_show).slideToggle(200);
        $(item_hide).slideToggle(200);
    });


    // Recursos -> Arquitectos
    if (section == 'empresa' && subsection == 'landingdisenyo') {

        landingDisenyo();

    } // Fin landing disenyo



    // Empresa -> Navidad
    if (section == 'noticias' && subsection == 'navidad') {
        var offsetPaneles;
        var triggerBebe;

        if ($(window).width() >= 768) {
            offsetPaneles = '-100';
            triggerBebe = 0.75;
        }

        if ($(window).width() > 1024) {
            offsetPaneles = '-145';
            triggerBebe = 0.33;
        }

        var typed = new Typed('.js-typed-navidad', {
          strings: strings_navidad_lang,
          typeSpeed: 50,
          backSpeed: 0,
          backDelay: 1250,
          loop: true,
          loopCount: false,
          showCursor: false
        });

        if ($(window).width() >= 768) {
            var controller = new ScrollMagic.Controller();

            function pathPrepare ($el) {
                var lineLength = $el[0].getTotalLength();
                $el.css("stroke-dasharray", lineLength);
                $el.css("stroke-dashoffset", lineLength);
            }

            var $hat = $("path#hat");
            pathPrepare($hat);

            var dialAnimation = new TimelineMax()
            .fromTo(".js-meses ul", 1, {x: "0%"}, {x: "-100%", ease: Linear.easeNone})

            var timelineAnimation = new TimelineMax()
            .fromTo(".js-navidad-paneles-content", 1, {x: "0%"}, {x: "-100%", ease: Linear.easeNone})

            var tweenHat = new TimelineMax()
                .add(TweenMax.to($hat, 0.9, {strokeDashoffset: 0, ease:Linear.easeNone}));

            // Add class design-comparte__left
            new ScrollMagic.Scene({
                triggerElement: ".js-hero-hat",
                duration: 400,
                tweenChanges: true,
                triggerHook: 0.75
            })
                .setTween(tweenHat)
                //.addIndicators()
                .addTo(controller);

            // Add class design-comparte__left
            new ScrollMagic.Scene({
                triggerElement: ".js-navidad-title",
                triggerHook: 0.45
            })
                .setClassToggle(".js-navidad-title", "is-active")
                //.addIndicators({name: 'intro title'})
                .addTo(controller);

            // Meses
            new ScrollMagic.Scene({
                triggerElement: ".js-trigger-meses",
                triggerHook: 'onLeave',
                offset: 20
                //duration: "8000px"
            })
                //.setClassToggle(".js-meses", "is-fixed")
                .setPin(".js-meses", {pushfollowers: false})
                .setTween(dialAnimation)
                //.addIndicators({name: 'meses'})
                .addTo(controller);

            // Meses (circle)
            new ScrollMagic.Scene({
                triggerElement: ".js-trigger-meses",
                triggerHook: 'onLeave',
                offset: 20,
                duration: "3000px"
            })
                .setClassToggle(".circle-wrap", "is-fixed")
                .setTween(dialAnimation)
                //.addIndicators({name: 'circulo año'})
                .addTo(controller);

            // Scroll horizontal paneles
            new ScrollMagic.Scene({
                triggerElement: ".js-navidad-paneles",
                triggerHook: 'onLeave',
                offset: offsetPaneles,
                duration: "2700px"
            })
            .setPin(".js-navidad-paneles", {pushfollowers: false})
            .setTween(timelineAnimation)
            // .addIndicators({
            //     name: 'paneles-molones',
            //     indent: 150,
            //     colorStart: 'orange',
            //     colorTrigger: 'orange'
            // })
            .addTo(controller);

            new ScrollMagic.Scene({
                triggerElement: ".js-navidad-growing",
                triggerHook: 'onLeave',
                offset: offsetPaneles
            })
                .setPin(".js-navidad-paneles", {pushfollowers: true})
                .setClassToggle(".js-navidad-paneles", "is-white")
                .addTo(controller);

            new ScrollMagic.Scene({
                triggerElement: ".js-navidad-growing",
                triggerHook: 'onLeave'
            })
                .setClassToggle(".js-meses", "hidden")
                //.addIndicators({name: 'growing'})
                .addTo(controller);

            new ScrollMagic.Scene({
                triggerElement: ".js-growing-chica",
                triggerHook: 0.45
            })
                .setClassToggle(".js-growing-chica", "is-active")
                .addTo(controller);

            new ScrollMagic.Scene({
                triggerElement: ".js-growing-premio",
                triggerHook: 0.45
            })
                .setClassToggle(".js-growing-premio", "is-active")
                .addTo(controller);

            new ScrollMagic.Scene({
                triggerElement: ".js-growing-vicente",
                triggerHook: 0.45
            })
                .setClassToggle(".js-growing-vicente", "is-active")
                .addTo(controller);

            new ScrollMagic.Scene({
                triggerElement: ".js-growing-bebe",
                triggerHook: triggerBebe
            })
                .setClassToggle(".js-growing-bebe", "is-active")
                .addTo(controller);

            new ScrollMagic.Scene({
                triggerElement: ".js-growing-logo",
                triggerHook: 0.6
            })
                .setClassToggle(".js-growing-logo", "is-active")
                .addTo(controller);

        }

    } // Fin Navidad

    // Empresa -> Navidad
    if (subsection == 'navidad18') {
        if ($(window).width() >= 768) {
            var controller = new ScrollMagic.Controller();

            new ScrollMagic.Scene({
                triggerElement: ".christmas-item--windows",
                triggerHook: 0.45
            })
                .setClassToggle(".js-windows-lines", "is-active")
                .addTo(controller);

            new ScrollMagic.Scene({
                triggerElement: ".christmas-item--light",
                triggerHook: 0.45
            })
                .setClassToggle(".js-light-lines", "is-active")
                .addTo(controller);

            new ScrollMagic.Scene({
                triggerElement: ".christmas-item--air",
                triggerHook: 0.45
            })
                .setClassToggle(".js-air-lines", "is-active")
                .addTo(controller);

            new ScrollMagic.Scene({
                triggerElement: ".christmas-item--air",
                triggerHook: 0.45
            })
                .setClassToggle(".js-air-lines", "is-active")
                .addTo(controller);

            new ScrollMagic.Scene({
                triggerElement: ".christmas-item--silence",
                triggerHook: 0.45
            })
                .setClassToggle(".js-silence-lines", "is-active")
                .addTo(controller);

            new ScrollMagic.Scene({
                triggerElement: ".christmas-item--move",
                triggerHook: 0.45
            })
                .setClassToggle(".js-move-lines", "is-active")
                .addTo(controller);

            new ScrollMagic.Scene({
                triggerElement: ".christmas-item--bio",
                triggerHook: 0.45
            })
                .setClassToggle(".js-bio-lines", "is-active")
                .addTo(controller);

            new ScrollMagic.Scene({
                triggerElement: ".christmas-item--fruit",
                triggerHook: 0.45
            })
                .setClassToggle(".js-fruit-lines", "is-active")
                .addTo(controller);

            new ScrollMagic.Scene({
                triggerElement: ".christmas-item--social",
                triggerHook: 0.45
            })
                .setClassToggle(".js-social-lines", "is-active")
                .addTo(controller);


            new ScrollMagic.Scene({
                triggerElement: ".js-water-boats",
                triggerHook: 0.45
            })
                .setClassToggle(".js-water-boats", "is-active")
                .addTo(controller);

            new ScrollMagic.Scene({
                triggerElement: ".js-water-star",
                triggerHook: 0.45
            })
                .setClassToggle(".js-water-star", "is-active")
                .addTo(controller);

            new ScrollMagic.Scene({
                triggerElement: ".js-water-people",
                triggerHook: 0.45
            })
                .setClassToggle(".js-water-people", "is-active")
                .addTo(controller);

            new ScrollMagic.Scene({
                triggerElement: ".js-water-clouds",
                triggerHook: 0.45
            })
                .setClassToggle(".js-water-clouds", "is-active")
                .addTo(controller);

            new ScrollMagic.Scene({
                triggerElement: ".js-water-personas",
                triggerHook: 0.75
            })
                .setClassToggle(".js-water-personas", "is-active")
                .addTo(controller);
        }
    }
});





// Quitados de main.js


function formContacto()
{
    var validationResult = true;
    var $form = $('.js-form-contact');
    var $alertOk = $form.find('.js-alert-ok');
    var $alertError = $form.find('.js-alert-error');

    $alertOk.addClass('hidden');
    $alertError.addClass('hidden');

    $form.find('.js-required').each(function() {
        $this = $(this);
        $this.val($.trim($this.val()));
        var val = $(this).val();

        if (val === '') {
            validationResult = false;
            $this.closest('.form-group').addClass('has-error');
        } else if ($this.attr('type') == 'email' && !validateEmail(val)) {
            validationResult = false;
            $this.closest('.form-group').addClass('has-error');
        } else if ($this.attr('type') == 'tel' && !validatePhone(val)) {
            validationResult = false;
            $this.closest('.form-group').addClass('has-error');
        } else if ($this.attr('type') == 'checkbox' && !$this.prop('checked')) {
            validationResult = false;
            $this.closest('.form-group').addClass('has-error');
        } else {
            $this.closest('.form-group').removeClass('has-error');
        }
    });

    if ($("input[name='motivo']:checked").length === 0)
    {
        validationResult = false;
        $("input[name='motivo']").closest('.form-group-radio').addClass('has-error');
    }
    else
    {
        $("input[name='motivo']").closest('.form-group-radio').removeClass('has-error');
    }

    if (!validationResult && $form.find('.has-error').length > 0) {
        $alertError.removeClass('hidden');
        /******************actiu_cambio
        $form.find('.has-error .js-required').first().focus();

        setTimeout(function() {
            $('html, body').animate({ scrollTop: $alertError.offset().top - $('.js-main-header').outerHeight() - 10 }, 300);
        }, 250);
        *****************************/
    }

    return validationResult;
}


function formNewsletter()
{
    var validationResult = true;
    var $form = $('.js-form-newsletter');
    var $alertOk = $form.find('.js-alert-ok');
    var $alertError = $form.find('.js-alert-error');

    $alertOk.addClass('hidden');
    $alertError.addClass('hidden');

    $form.find('.js-required').each(function() {
        $this = $(this);
        $this.val($.trim($this.val()));
        var val = $(this).val();

        if (val === '') {
            validationResult = false;
            $this.closest('.form-group').addClass('has-error');
        } else if ($this.attr('type') == 'email' && !validateEmail(val)) {
            validationResult = false;
            $this.closest('.form-group').addClass('has-error');
        } else if ($this.attr('type') == 'checkbox' && !$this.prop('checked')) {
            validationResult = false;
            $this.closest('.form-group').addClass('has-error');
        } else {
            $this.closest('.form-group').removeClass('has-error');
        }
    });

    if (!validationResult && $form.find('.has-error').length > 0) {
        $alertError.removeClass('hidden');
        $form.find('.has-error .js-required').first().focus();
        /*
        setTimeout(function() {
            $('html, body').animate({ scrollTop: $alertError.offset().top - $('.js-main-header').outerHeight() - 10 }, 300);
        }, 250);
        */
    }

    return validationResult;
}


function formEmpleoCv()
{
    var validationResult = true;
    var $form = $('.js-form-cv');
    var $alertOk = $form.find('.js-alert-ok');
    var $alertError = $form.find('.js-alert-error');

    $alertOk.addClass('hidden');
    $alertError.addClass('hidden');


    $form.find('.js-required').each(function() {
        $this = $(this);
        var val = $.trim($(this).val());
        var id = $(this).attr("id");

        $this.closest('.form-group').removeClass('has-error');
        $this.closest('.form-group--mb-extra').removeClass('has-error');

        if (id.indexOf("plantilla") == -1 && id.indexOf("empresa") == -1 && id.indexOf("experiencia") == -1) {
            if ($this.attr('type') == 'email' && !validateEmail(val)) { //................E-mail
                validationResult = false;
                $this.closest('.form-group').addClass('has-error');
            } else if (id == "pais") { //.................................................Otro país
                if ($("#id_pais").val() == "Otros" && val === "") {
                    validationResult = false;
                    $this.closest('.form-group').addClass('has-error');
                } else {
                    $this.closest('.form-group').removeClass('has-error');
                }
            } else if (id == "provincia") { //............................................Provincia
                if ($("#id_pais").val() == "España" && val === "") {
                    validationResult = false;
                    $this.closest('.form-group').addClass('has-error');
                } else {
                    $this.closest('.form-group').removeClass('has-error');
                }
            } else if (id == "foto_reciente") { //........................................Foto
                archivo = val;
                extension = (archivo.substring(archivo.lastIndexOf("."))).toLowerCase();
                if(extension != ".jpg" && extension != ".jpeg" && extension != ".png") {
                    validationResult = false;
                    $this.closest('.form-group').addClass('has-error');
                } else {
                    $this.closest('.form-group').removeClass('has-error');
                }
            } else if (id == "cv") { //...................................................Curriculum
                archivo = val;
                extension = (archivo.substring(archivo.lastIndexOf("."))).toLowerCase();
                if(extension != ".doc" && extension != ".docx" && extension != ".pdf") {
                    validationResult = false;
                    $this.closest('.form-group').addClass('has-error');
                } else {
                    $this.closest('.form-group').removeClass('has-error');
                }
            } else if (id == "condiciones" && $(this).is(":checked") === false) { //.......Condiciones
                validationResult = false;
                $this.closest('.form-group').addClass('has-error');
            } else if (val === '') { //....................................................Resto de campos
                validationResult = false;
                $this.closest('.form-group').addClass('has-error');
            }
        }

    });

    if ($("#no_experiencia").is(":checked") === false){
        //...............................................................................Empresa y experiencia
        var hayAlgunaEmpresa = false;
        $.each($("[name='empresa[]']"),function(ind,elemento) {
            var valor = $.trim($(this).val());
            var indice = $(this).attr("data-actiu_indice");
            if (valor !== "") {
                hayAlgunaEmpresa = true;
                if ($("[id^='experiencia'][data-actiu_indice='" + indice + "']").val() === "") {
                    validationResult = false;
                    $("[id^='experiencia'][data-actiu_indice='" + indice + "']").closest('.form-group--mb-extra').addClass('has-error');
                }
            }
        });

        if (hayAlgunaEmpresa === false){
            validationResult = false;
            $("#empresa").closest('.form-group').addClass('has-error');
            $("#experiencia").closest('.form-group--mb-extra').addClass('has-error');
        }

    }


    if (!validationResult && $form.find('.has-error').length > 0) {
        $alertError.removeClass('hidden');
        /******************actiu_cambio
        $form.find('.has-error .js-required').first().focus();

        setTimeout(function() {
            $('html, body').animate({ scrollTop: $alertError.offset().top - $('.js-main-header').outerHeight() - 10 }, 300);
        }, 250);
        *****************************/
    }

    return validationResult;
}




// Search

var myVarTimeout = null;
var lastSearchInputVal = '';

function searchAction()
{
    $('.js-search-subtitle').css('opacity', 1);
    $('.js-search-results, .js-search-loading, .js-search-msg, .js-search-list').hide();

    if( $searchInput.val() !== '' && $searchInput.val().length >= 3 )
    {
        $('body').addClass('is-blocked');
        $('.js-search-backdrop').show();
        // alert($searchInput.val());

        $('.js-search-subtitle').css('opacity', 0);
        $('.js-search-main').show();
        $('.js-search-results, .js-search-loading').show();

        clearTimeout(myVarTimeout);

        // AJAX Call
        myVarTimeout = setTimeout(function()
        {
            // $('.js-search-loading').hide();
            // $('.js-search-msg, .js-search-list').show();

            _action_search = $("#action_search").val() + $searchInput.val() + '/todos/1';

            lastSearchInputVal = $searchInput.val();

            // obtiene texto plano o html
            $.get(_action_search, function(resp)
            {
                if( lastSearchInputVal == $searchInput.val() )
                {
                    $('.js-search-loading').hide();
                    $('.js-search-msg, .js-search-list').show();
                    $('.js-search-list').html(resp);
                    $('.js-search-msg').html($('#resumen_search').html());
                }
            });

        }, 1000);

    } else {
        $('body').removeClass('is-blocked');
        $('.js-search-main, .js-search-backdrop').fadeOut(250);
    }
}

function pageSearchAction(_action_search)
{
    // _action_search = $("#action_search").val() + $searchInput.val() + '/todos/1';
    $('.js-search-results, .js-search-loading').show();

    // obtiene texto plano o html
    $.get(_action_search, function(resp)
    {
        // console.log(resp);
        $('.js-search-loading').hide();
        $('.js-search-msg, .js-search-list').show();
        $('.js-search-list').html(resp);

        $('.js-search-msg').html($('#resumen_search').html());
    });
}

function pageDisenyoActualidadAction(_action_search, _page)
{
    // acciones a realizar mientras se espera la respuesta del server
    $('#div_disenyo_actualidad').html('<img class="search__loading loading animation-spin js-search-loading" src="/images/icons/loading.svg" width="30" height="30" alt="Loading..." >');

    $("html, body").animate({scrollTop:$('#div_disenyo_actualidad').offset().top-$(".js-main-header").outerHeight()},300);

    // obtiene texto plano o html
    $.post(_action_search, {_page:_page},  function(resp)
    {
        // console.log(resp);
        $("#div_disenyo_actualidad").html(resp);

        destroyLandingDisenyo(); // Reseteamos la escena de Scrollmagic
        landingDisenyo(); // Volvemos a crear la escena de Scrollmagic
        lightboxVideo(); // Volvemos a llamar a la función para el lightbox del video
    });
}
